<template>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <!-- 搜索表单区域 -->
        <ElCard class="card-wrapper">
            <ElForm :model="searchParams" label-position="right" :label-width="80">
                <ElRow :gutter="24">
                    <ElCol :lg="6" :md="8" :sm="12">
                        <ElFormItem label="文章标题" prop="searchTitle">
                            <ElInput v-model="searchParams.searchTitle" placeholder="请输入（模糊查询）" clearable />
                        </ElFormItem>
                    </ElCol>
                    <ElCol :lg="8" :md="12" :sm="24">
                        <ElFormItem label="发布日期">
                            <ElDatePicker
                                v-model="searchParams.pickDate"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                :shortcuts="shortcuts"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                @change="datepickerChange"
                            />
                        </ElFormItem>
                    </ElCol>
                    <ElCol :lg="6" :md="8" :sm="12">
                        <ElFormItem>
                            <ElSpace>
                                <ElButton type="primary" :icon="Search" @click="getTableData">查询</ElButton>
                                <ElButton :icon="RefreshRight" @click="reset">重置</ElButton>
                            </ElSpace>
                        </ElFormItem>
                    </ElCol>
                </ElRow>
            </ElForm>
        </ElCard>

        <!-- 表格卡片区域 -->
        <ElCard class="flex-1 card-wrapper">
            <template #header>
                <div class="flex items-center justify-between">
                    <p>文章管理</p>
                    <ElButton type="primary" @click="handleAdd">
                        <template #icon>
                            <EditPen />
                        </template>
                        写文章
                    </ElButton>
                </div>
            </template>
            
            <div class="table-container">
                <ElTable
                    v-loading="tableLoading"
                    border
                    :data="tableData"
                    row-key="id"
                    style="width: 100%"
                    :height="400"
                >
                    <ElTableColumn type="index" label="序号" width="60" align="center" />
                    <ElTableColumn prop="title" label="标题" min-width="200" show-overflow-tooltip />
                    <ElTableColumn label="预览图" width="100" align="center">
                        <template #default="scope">
                            <ElImage 
                                v-if="scope.row.titleImage"
                                style="width: 40px; height: 40px; border-radius: 4px;" 
                                :src="scope.row.titleImage" 
                                fit="cover"
                                :preview-src-list="[scope.row.titleImage]"
                            />
                            <span v-else class="text-gray-400">无图片</span>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn prop="createTime" label="发布时间" width="160" align="center" />
                    <ElTableColumn label="操作" width="200" align="center" fixed="right">
                        <template #default="scope">
                            <ElSpace>
                                <ElButton type="primary" size="small" @click="handleEdit(scope.row)">
                                    <template #icon>
                                        <Edit />
                                    </template>
                                    编辑
                                </ElButton>
                                <ElButton size="small" @click="previewArticle(scope.row)">
                                    <template #icon>
                                        <View />
                                    </template>
                                    预览
                                </ElButton>
                                <ElButton type="danger" size="small" @click="deleteArticleSubmit(scope.row)">
                                    <template #icon>
                                        <Delete />
                                    </template>
                                    删除
                                </ElButton>
                            </ElSpace>
                        </template>
                    </ElTableColumn>
                </ElTable>
            </div>
            
            <div class="pagination-container">
                <ElPagination
                    v-model:current-page="current"
                    v-model:page-size="size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    :page-sizes="[10, 20, 50, 100]"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                />
            </div>
        </ElCard>

        <!-- 文章编辑对话框 -->
        <ArticleEditDialog 
            ref="articleDialogRef"
            @success="handleDialogSuccess" 
        />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getArticlePageList, deleteArticle } from '@/service/api/blog/AdminCategoryController'
import { getCategorySelect } from '@/service/api/blog/classificationman'
import { showMessage } from '@/composables/util'
import { useRouter } from 'vue-router'
import { Search, RefreshRight, EditPen, Edit, View, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import ArticleEditDialog from './modules/ArticleEditDialog.vue'

defineOptions({ name: 'ArticleManage' })

const router = useRouter()
const articleDialogRef = ref()

const tableLoading = ref(false)
const categories = ref([])

// 搜索参数
const searchParams = reactive({
    searchTitle: '',
    pickDate: '',
    startDate: '',
    endDate: ''
})

const reset = () => {
    searchParams.searchTitle = ''
    searchParams.pickDate = ''
    searchParams.startDate = ''
    searchParams.endDate = ''
    current.value = 1
    getTableData()
}

const datepickerChange = (dates: any) => {
    if (dates && dates.length === 2) {
        searchParams.startDate = dates[0]
        searchParams.endDate = dates[1]
    } else {
        searchParams.startDate = ''
        searchParams.endDate = ''
    }
}

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

const previewArticle = (row: any) => {
    const routeData = router.resolve({ path: '/article/detail', query: { articleId: row.id } })
    window.open(routeData.href, '_blank')
}

const tableData = ref<any[]>([])
const current = ref(1)
const total = ref(0)
const size = ref(10)

// 获取分页数据
async function getTableData() {
    try {
        tableLoading.value = true
        const params = {
            current: current.value,
            size: size.value,
            startDate: searchParams.startDate || undefined,
            endDate: searchParams.endDate || undefined,
            searchTitle: searchParams.searchTitle || undefined
        }
        
        console.log('请求参数:', params)
        const res = await getArticlePageList(params)
        console.log('响应数据:', res)
        
        if (res && res.data) {
            const data = res.data
            tableData.value = data.records || data.list || []
            total.value = data.total || 0
            current.value = data.current || current.value
            size.value = data.size || size.value
            
            console.log('表格数据:', tableData.value)
            console.log('总数:', total.value)
        } else {
            showMessage(res?.message || '获取数据失败', 'error')
            tableData.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取数据失败:', error)
        showMessage('获取数据失败', 'error')
        tableData.value = []
        total.value = 0
    } finally {
        tableLoading.value = false
    }
}

// 获取分类数据
async function loadCategories() {
    try {
        const res = await getCategorySelect()
        if (res.data) {
            categories.value = res.data.map((item: any) => ({
                id: item.value || item.id,
                name: item.label || item.name
            }))
        }
    } catch (error) {
        console.error('获取分类数据失败:', error)
    }
}

// 初始化数据
onMounted(() => {
    getTableData()
    loadCategories()
})

const handleCurrentChange = (newCurrent: number) => {
    console.log('页码变化:', newCurrent)
    current.value = newCurrent
    getTableData()
}

const handleSizeChange = (newSize: number) => {
    console.log('页面大小变化:', newSize)
    size.value = newSize
    current.value = 1
    getTableData()
}

// 新增文章
const handleAdd = () => {
    if (articleDialogRef.value) {
        articleDialogRef.value.open('add', null, categories.value)
    }
}

// 编辑文章
const handleEdit = (row: any) => {
    if (articleDialogRef.value) {
        articleDialogRef.value.open('edit', row, categories.value)
    }
}

// 对话框成功回调
const handleDialogSuccess = () => {
    getTableData()
}

const deleteArticleSubmit = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            '是否确认要删除该文章?',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        
        const res = await deleteArticle(row.id)
        if (res && res.success !== false) {
            showMessage('删除成功', 'success')
            getTableData()
        } else {
            showMessage(res?.message || '删除失败', 'error')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            showMessage('删除失败', 'error')
        }
    }
}
</script>

<style lang="scss" scoped>
.card-wrapper {
  height: 100%;
  
  :deep(.el-card__body) {
    height: calc(100% - 60px);
    display: flex;
    flex-direction: column;
  }
}

.table-container {
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: var(--el-fill-color-light);
      font-weight: 600;
    }
  }
  
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: var(--el-fill-color-lighter);
      }
    }
  }
}
</style>